package mybaidu

import (
	"data/config"
	"data/view/user"
	"data/view/weixin"
	"public/message"
	"public/mysqldb"
	"public/tools"

	"github.com/ant0ine/go-json-rest/rest"
)

//ocr关联
func OnCheckOcr(w rest.ResponseWriter, r *rest.Request) {
	// var res Res_checkOcr
	// res.Url = "/recruitserver/file/idcard/511324198807180036.png"
	// res.Id_card = "511324198807180036"
	// msg := message.GetSuccessMsg()
	// msg.Data = res
	// w.WriteJson(msg)
	// return

	var req map[string]string
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req["url"]) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	req["url"] = req["url"][len(config.Url_host)+1:]

	info := GetIdCardInfo(req["url"])

	if info.Image_status == "normal" && info.Words_result_num == 6 {
		//保存ocr
		var ocr_card Ocr_card
		ocr_card.Id_card = info.Words_result.IDCard.Words
		ocr_card.Id_card_location = tools.GetJsonStr(&info.Words_result.IDCard.Location)
		ocr_card.Addr = info.Words_result.Addr.Words
		ocr_card.Addr_location = tools.GetJsonStr(&info.Words_result.Addr.Location)
		ocr_card.Birth = info.Words_result.Birth.Words
		ocr_card.Birth_location = tools.GetJsonStr(&info.Words_result.Birth.Location)
		ocr_card.Name = info.Words_result.Name.Words
		ocr_card.Name_location = tools.GetJsonStr(&info.Words_result.Name.Location)
		ocr_card.Sex = info.Words_result.Sex.Words
		ocr_card.Sex_location = tools.GetJsonStr(&info.Words_result.Sex.Location)
		ocr_card.Nation = info.Words_result.Addr.Words
		ocr_card.Nation_location = tools.GetJsonStr(&info.Words_result.Nation.Location)
		ocr_card.Url = req["url"]
		var db mysqldb.MySqlDB
		defer db.OnDestoryDB()
		orm := db.OnGetDBOrm(config.GetDbUrl())
		orm.Save(&ocr_card)
		//---------------end
		var res Res_checkOcr
		res.Url = OnSaveIdCard(info)
		res.Id_card = info.Words_result.IDCard.Words
		msg := message.GetSuccessMsg()
		msg.Data = res
		w.WriteJson(msg)
	} else {
		w.WriteJson(message.GetErrorMsg(message.NotFindError, "请正确拍摄身份证正面信息."))
	}
}

//ocr关联
func OnBindOcr(w rest.ResponseWriter, r *rest.Request) {
	var req Req_OcrBind
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Id_card, req.Open_id, req.Type) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}

	//先获取openid信息
	info := weixin.OnGetUserInfo(req.Open_id, req.Type)
	if info.Id <= 0 {
		w.WriteJson(message.GetErrorMsg(message.NotFindError, "未找到绑定信息"))
		return
	}

	//获取用户信息
	_, b := user.GetUserDetail(req.Id_card)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.NotFindError, "此账号未注册,请先注册账号"))
		return
	}

	//开始绑定
	info.Username = req.Id_card
	weixin.UpdateInfo(info)

	//返回绑定成功
	w.WriteJson(message.GetSuccessMsg())
	return
}
